//
//  SearchViewController.m
//  WuJieLive
//
//  Created by 张瀚坤 on 2017/10/24.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "SearchViewController.h"
#import "GoodsListViewController.h"

@interface SearchViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , strong) UITextField * textField;

@property (nonatomic , strong) UITableView * tableView;

@property (nonatomic , strong) NSMutableArray * array;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}


- (void)setNavi
{
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 80, 30)];
    view.backgroundColor = Color(237, 237, 237);
    [view setCorner:15.f];
    self.navigationItem.titleView = view;
    
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(15, 0, kScreenWidth - 80, 32)];
    [view addSubview:self.textField];
    self.textField.delegate = self;
    self.textField.backgroundColor = [UIColor clearColor];
    self.textField.placeholder = @" 搜索";
    [self.textField setValue:FontSize(13) forKeyPath:@"_placeholderLabel.font"];
    UIImageView * leftView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 13, 13)];
    leftView.image = Image(@"icon_nav_搜索");
    self.textField.leftView = leftView;
    self.textField.leftViewMode = UITextFieldViewModeUnlessEditing;
    self.textField.returnKeyType = UIReturnKeySearch;
    self.textField.enablesReturnKeyAutomatically = YES;
    self.textField.textColor = Color(51, 51, 51);
    self.textField.font = FontSize(13);
    [self.textField becomeFirstResponder];
    
}

- (void)setUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;//  是表视图从导航条下开始布局显示
    self.view.backgroundColor = Color(237, 237, 237);
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44)];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.array = [NSMutableArray array];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"historyArray"]) {
        [self.array addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"historyArray"]];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (self.array.count > indexPath.row) {
        cell.textLabel.text = self.array[self.array.count - indexPath.row - 1];
        cell.textLabel.textColor = TextLessImportColor;
    }
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 100, 50)];
        [view addSubview:label];
        label.text = @"最近搜索";
        UIButton * btn = [[UIButton alloc]init];
        [view addSubview:btn];
        [btn setBackgroundImage:Image(@"icon_垃圾桶") forState:(UIControlStateNormal)];
        btn.frame = CGRectMake(CGRectGetMaxX(view.frame) - 50, 15, 20, 20);
        [btn addTarget:self action:@selector(deleteData) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        return view;
    }else
    {
        return nil;
    }
}

- (void)deleteData
{
    [self.array removeAllObjects];
    [self.tableView reloadData];
    [[NSUserDefaults standardUserDefaults] setObject:self.array forKey:@"historyArray"];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length > 0) {
        
        [self deleteHistoryWithString:textField.text];
        
        GoodsListViewController *vc = [GoodsListViewController new];
        vc.keywordStr = textField.text;
        [self.navigationController pushViewController:vc animated:YES];
        
        return YES;
    }else
    {
        return NO;
    }
}

- (void)deleteHistoryWithString:(NSString *)string
{
    // 利用block来操作数组 如果边遍历数组 边操作数组会造成crash 利用block更快更高效
    [self.array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:string]) {
            *stop = YES;
            if (*stop) {
                [self.array removeObject:obj];
            }
        }
    }];
    [self.array addObject:string];
    [[NSUserDefaults standardUserDefaults] setObject:self.array forKey:@"historyArray"];
    [self.tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 50;
    }else
    {
        return 0;
    }
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    self.textField.text = self.array[self.array.count - indexPath.row - 1];
    [self deleteHistoryWithString:self.array[self.array.count - indexPath.row - 1]];
    
    GoodsListViewController *vc = [GoodsListViewController new];
    vc.keywordStr = self.textField.text;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)leftBtnAction:(UIButton *)sender
{
    [self.textField resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
//{
//    [self.textField resignFirstResponder];
//}

@end
